//
//  HubuShelfViewController.m
//  iHubu2
//
//  Created by hanshui on 12-11-2.
//  Copyright (c) 2012年 hanshui. All rights reserved.
//

#import "HubuShelfViewController.h"
#import "BookItem.h"
#import "DBUtil.h"
#import "BookConstants.h"
#import "BookReadView2.h"

@interface HubuShelfViewController ()

@end

@implementation HubuShelfViewController
@synthesize listScrollView, bookshelfEditView, bookshelfRemoveView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [listScrollView setContentSize:CGSizeMake(320, 800)];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(IBAction)backStoreClick:(id)sender {
    //[self dismissModalViewControllerAnimated:YES];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)paintSheetBackground {
    for(int i = 0; i < 3; i++) {
        UIImageView *mainBg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 395 * i, 320, 395)];
        mainBg.image = [UIImage imageNamed:@"book_shelf_bg.png"];
        [listScrollView addSubview:mainBg];
        [mainBg release];
    }
}


-(void)showBookStoreView {
    if(![self isViewLoaded]) {
        [self loadView];
    }
    
    [self paintSheetBackground];
    
//    for(UIView *subview in [listScrollView subviews]) {
//        if(![subview isKindOfClass:NSClassFromString(@"UIImageView")]){
//            [subview removeFromSuperview];
//        }
//    }
    
    if(buyBookData == nil){
        buyBookData = [[NSMutableArray alloc] initWithCapacity:20];
    }else{
        [buyBookData removeAllObjects];
    }
    
    //获取当前栏目的数据
    DBUtil *db = [[DBUtil alloc] init];
    [db openDB];
    [db getMyData:buyBookData page:@"1" keyword:@""];
    [db closeDB];
    [db release];
    
    int rowHeight = 126;
    int columnWidth = 91;
    int rowCount = 0;
    int columnIndex = 0;
    int topSpacing = 10;
    int leftSpacing = 15;
    
    for(int i=0;i < [buyBookData count];i++){
        rowCount = i / 3;
        columnIndex = i % 3;
        BookReadView2 *bookItemView2 = [[[NSBundle mainBundle] loadNibNamed:@"BookReadView2" owner:self options:nil] objectAtIndex:0];
        [bookItemView2 initExtend:[[buyBookData objectAtIndex:i] mutableCopy]];
        //bookItemView2.parentObject = self;
        [bookItemView2 setFrame:CGRectMake(columnIndex * columnWidth + 7 + columnIndex * 6 + leftSpacing,
                                           rowCount * rowHeight + rowCount * 6 + topSpacing, 90, 120)];
        [listScrollView addSubview:bookItemView2];
    }
    
    [bookshelfEditView setHidden:NO];
    [bookshelfRemoveView setHidden:YES];
}


-(void)bookStoreRepaint {
    int rowHeight = 126;
    int columnWidth = 91;
    int rowCount = 0;
    int columnIndex = 0;
    int topSpacing = 10;
    int leftSpacing = 15;
    
    for(int i=0;i < [buyBookData count];i++){
        rowCount = i / 3;
        columnIndex = i % 3;
        BookReadView2 *bookItemView2 = [[[NSBundle mainBundle] loadNibNamed:@"BookReadView2" owner:self options:nil] objectAtIndex:0];
        [bookItemView2 initExtend:[[buyBookData objectAtIndex:i] mutableCopy]];
        //bookItemView2.parentObject = self;
        [bookItemView2 setFrame:CGRectMake(columnIndex * columnWidth + 7 + columnIndex * 6 + leftSpacing,
                                           rowCount * rowHeight + rowCount * 6 + topSpacing, 90, 120)];
        [listScrollView addSubview:bookItemView2];
    }
}


-(IBAction)changeBookshelfToolbar:(id)sender {
    int tag = [(UIButton *)sender tag];
    if(tag == 1){
        [bookshelfEditView setHidden:YES];
        [bookshelfRemoveView setHidden:NO];
        
        for(UIView *subview in [listScrollView subviews]) {
            if([subview isKindOfClass:NSClassFromString(@"BookReadView2")]){
                BookReadView2 *bookReadView = (BookReadView2 *)subview;
                [bookReadView.deleteSelectedButton setEnabled:YES];
                [bookReadView.deleteSelectedButton setHidden:NO];
                bookReadView.bookDelete = FALSE;
            }
        }
    }else{
        for(UIView *subview in [listScrollView subviews]) {
            if([subview isKindOfClass:NSClassFromString(@"BookReadView2")]){
                BookReadView2 *bookReadView = (BookReadView2 *)subview;
                [bookReadView.deleteSelectedButton setImage:nil forState:UIControlStateNormal];
                [bookReadView.deleteSelectedButton setEnabled:NO];
                [bookReadView.deleteSelectedButton setHidden:YES];
                bookReadView.bookDelete = FALSE;
            }
        }
        [bookshelfRemoveView setHidden:YES];
        [bookshelfEditView setHidden:NO];
    }
}

-(IBAction)deleteBookshelfClick:(id)sender {
    // confirm the deletion..
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle: @"确认要删除选中的图书吗？"
                          message: @""
                          delegate: self
                          cancelButtonTitle: @"取消"
                          otherButtonTitles: @"删除", nil];
    [alert show];
    [alert release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        NSMutableArray *deleteArray = [[NSMutableArray alloc] initWithCapacity:5];
        for(UIView *subview in [listScrollView subviews]) {
            if([subview isKindOfClass:NSClassFromString(@"BookReadView2")]){
                BookReadView2 *bookReadView = (BookReadView2 *)subview;
                if(bookReadView.bookDelete){
                    [deleteArray addObject:[NSString stringWithFormat:@"%@",  bookReadView.localBookItem.bookId]];
                    
                    //删除文件
                    NSString *fileName = @"";
                    if([bookReadView.localBookItem book4PhoneResourceType] != nil && ![[bookReadView.localBookItem book4PhoneResourceType] isEqualToString:@""]) {
                        fileName = [[bookReadView.localBookItem book4PhoneResource] stringByDeletingPathExtension];
                        fileName = [NSString stringWithFormat:@"%@.%@",fileName, [bookReadView.localBookItem book4PhoneResourceType]];
                    }else{
                        fileName = [[bookReadView.localBookItem book4PadResource] stringByDeletingPathExtension];
                        fileName = [NSString stringWithFormat:@"%@.%@",fileName, [bookReadView.localBookItem book4PadResourceType]];
                    }
                    
                    NSError *error;
                    NSString *filePath=[kDocumentFolder stringByAppendingPathComponent:fileName];
                    if([[NSFileManager defaultManager] fileExistsAtPath:filePath]){
                        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
                    }
                    
                    [subview removeFromSuperview];
                }
            }
        }
        
        
        if([deleteArray count] > 0) {
            //删除并重新获取当前栏目的数据
            DBUtil *db = [[DBUtil alloc] init];
            [db openDB];
            [db batchDeleteBook:deleteArray];
            [buyBookData removeAllObjects];
            [db getMyData:buyBookData page:@"1" keyword:@""];
            [db closeDB];
            [db release];
            
            //删除Scroll View 的所有内容
            for(UIView *subview in [listScrollView subviews]) {
                if(![subview isKindOfClass:NSClassFromString(@"UISearchBar")] &&
                   ![subview isKindOfClass:NSClassFromString(@"UIImageView")]){
                    [subview removeFromSuperview];
                }
            }
            [self bookStoreRepaint];
        }
        [deleteArray release];
    } else {
        //NSLog(@"取消删除");
        // be nice with the world, maybe initiate some Ecological action as a bonus
    }
}
@end
